const baseController = require('./base');
const testModel = require('../model/test');
const uploadFile = require('../util/upload');
const svgCaptcha = require('svg-captcha');

class testController extends baseController {

    static async index(ctx) {

        let count = ctx.$cache.get('test');
        if (count == null) {
            count = await testModel.getUserNum(ctx);
            if (count) {
                ctx.$cache.put('test', count, 10000);
            }
        }
        //ctx.body = count;
        //ctx.body = ctx.$get;
        //ctx.body = await super.init(ctx);
        ctx.error('抛一个错误');
    }

    static async captcha(ctx, next) {
        let sign = ctx.$get.sign; //随机签名
        if (!sign) {
            return ctx.error('验证码缺少签名', 400);
        }
        if (ctx.$cache.get(sign) != null) {
            return ctx.error('验证码签名重复', 400);
        }
        let captcha = svgCaptcha.create();
        ctx.$cache.put(sign, captcha.text, 600000); //验证码有效期10分钟
        ctx.type = 'image/svg+xml';
        ctx.body = captcha.data;
    }

    static async verify(ctx) {
        if (ctx.method === 'GET') {
            let html = `
                <h1>koa2 data verify</h1>
                <form method="POST" action="/test/verify?id=1">
                    <p>data verify</p>
                    <input name="name" type="text" /><br/>
                    <input name="email" type="text" /><br/>
                    <input name="mobile" type="text" /><br/>
                    <button type="submit">submit</button>
                </form>
                `;
            ctx.body = html;
        } else {
            ctx.body = ctx.$param;
        }
    }

    static async html(ctx) {
        if (ctx.method === 'GET') {
            let html = `
                <h1>koa2 file upload</h1>
                <form method="POST" action="/test/upload" enctype="multipart/form-data">
                    <p>file upload</p>
                    <input name="file" type="file" /><br/><br/>
                    <button type="submit">submit</button>
                </form>
                `;
            ctx.body = html;
        }
    }

    static async upload(ctx) {
        let result = await uploadFile(ctx);
        ctx.body = result;
    }

}

module.exports = testController;